/*
 * @lc app=leetcode.cn id=1008 lang=cpp
 * @lcpr version=30204
 *
 * [1008] 前序遍历构造二叉搜索树
 */

// @lcpr-template-start
using namespace std;
#include <algorithm>
#include <array>
#include <bitset>
#include <climits>
#include <deque>
#include <functional>
#include <iostream>
#include <list>
#include <queue>
#include <stack>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
// @lcpr-template-end
struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
// @lc code=start

class Solution
{
public:
    TreeNode *bstFromPreorder(vector<int> &preorder)
    {
        return buildTree(preorder.begin(), preorder.end());
    }

    TreeNode *buildTree(vector<int>::iterator be, vector<int>::iterator en)
    {
        if (be >= en)
            return nullptr;
        TreeNode *root = new TreeNode(*be);
        auto it = be + 1;
        for (; it < en && *it < root->val; it++)
        {
        }
        root->left = buildTree(be + 1, it);
        root->right = buildTree(it, en);
        return root;
    }
};
// @lc code=end

/*
// @lcpr case=start
// [8,5,1,7,10,12]\n
// @lcpr case=end

// @lcpr case=start
// [1,3]\n
// @lcpr case=end

 */
